package com.laboratory.manage.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laboratory.manage.dao.CopyrightDao;
import com.laboratory.manage.entity.CopyrightEntity;
import com.laboratory.manage.service.CopyrightService;
import com.laboratory.manage.utils.FileUtils;
import com.laboratory.manage.utils.PageUtils;
import com.laboratory.manage.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;
import java.util.Map;

@Service
public class CopyrightServiceImpl extends ServiceImpl<CopyrightDao, CopyrightEntity> implements CopyrightService {

    @Autowired
    private CopyrightDao copyrightDao;

    @Value("${file.upload-dir}")
    private String uploadPath;

    @Override
    public boolean deleteByIds(Long[] ids) {
        for (int i = 0; i < ids.length; i++) {
            CopyrightEntity copyrightEntity = copyrightDao.selectById(ids[i]);
            //获取存储的路径
            String copyrightPath = copyrightEntity.getCopyrightPath();
            //获取作者路径
            String prePath = FileUtils.extractDirectory(copyrightPath);
            File file1 = new File(prePath);
            //获取以名字结尾的文件夹路径
            File file = new File(copyrightPath);
            if (file.exists()){
                file.delete();
                copyrightDao.deleteById(ids[i]);
            }
            //作者目录下没有论文后，删除作者目录
            if (file1 .isDirectory() && file1 .list().length == 0){
                file1.delete();
            }
        }

        return true;
    }

    //分页查询
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CopyrightEntity> page = this.page(new Query<CopyrightEntity>().getPage(params),
                new QueryWrapper<CopyrightEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public void upLoadFile(CopyrightEntity copyrightEntity) {
        this.baseMapper.insert(copyrightEntity);
    }

    @Override
    public void updateCopyright(CopyrightEntity copyrightEntity) {
        Date date = new Date();
        copyrightEntity.setUpdateTime(date);
        this.baseMapper.updateById(copyrightEntity);
    }


}
